package com.atguigu.jxc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.jxc.dao.DamageListDao;
import com.atguigu.jxc.dao.DamageListGoodsDao;
import com.atguigu.jxc.entity.DamageList;
import com.atguigu.jxc.entity.DamageListGoods;
import com.atguigu.jxc.entity.User;
import com.atguigu.jxc.service.DamageListGoodsService;
import com.atguigu.jxc.util.AuthContextHolder;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DamageListGoodsServiceImpl implements DamageListGoodsService {

    @Autowired
    private DamageListGoodsDao damageListGoodsDao;

    @Autowired
    private DamageListDao damageListDao;

    //保存报损单
    //damageNumber=BS1605766644460（报损单号,前端生成）
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(DamageList damageList, String damageListGoodsStr, HttpSession session) {
//        //获取当前登录的用户名
//        //根据用户名查询用户信息
        User userInfo = AuthContextHolder.getUserInfo(session);
        //保存报损单damageList
        damageList.setUserId(userInfo.getUserId());
        damageList.setTrueName(userInfo.getTrueName());
        damageListDao.saveDamageList(damageList);
        //保存报损单商品damageListGoods
        //把字符串damageListGoodsStr 转为对象 DamageListGoods JSONObject.parseArray
        List<DamageListGoods> damageListGoods = JSONObject.parseArray(damageListGoodsStr, DamageListGoods.class);
        damageListGoods.forEach(item -> {
            System.out.println(item);
            item.setDamageListId(damageList.getDamageListId());
            damageListGoodsDao.saveDamageListGoods(item);
        });
    }

    //查询报损单商品信息 Integer damageListId（报损单Id）
    @Override
    public Map<String, Object> goodsList(Integer damageListId) {
        List<DamageListGoods> damageListGoodsList=damageListGoodsDao.goodsList(damageListId);
        Map<String, Object> map=new HashMap<>();
        map.put("rows",damageListGoodsList);
        return map;
    }
}
